<template>
  <div id="info">
    <el-card style="width: 80%; margin: 0 auto">
      <el-row :gutter="2">
        <el-col :span="6">
          <el-avatar
            :alt="'无'"
            :shape="'square'"
            :size="200"
            :src="userDetail?.avatar"
            lazy
          />
        </el-col>
        <el-col :span="18">
          <el-descriptions
            :column="2"
            :label-width="150"
            border
            size="large"
            title="个人信息"
          >
            <template #extra>
              <el-button type="primary" @click="openUpdateModel"
                >修改个人信息
              </el-button>
              <el-button type="danger" @click="openUpdatePwd"
                >修改密码
              </el-button>
            </template>
            <el-descriptions-item align="center" label="账号">
              <el-text>{{ userDetail?.username }}</el-text>
            </el-descriptions-item>
            <el-descriptions-item align="center" label="昵称">
              <el-text>{{ userDetail?.nickname }}</el-text>
            </el-descriptions-item>
            <el-descriptions-item align="center" label="邮箱">
              <el-text>{{ userDetail?.email || "无" }}</el-text>
            </el-descriptions-item>
            <el-descriptions-item align="center" label="电话">
              <el-text>{{ userDetail?.phone || "无" }}</el-text>
            </el-descriptions-item>
            <el-descriptions-item align="center" label="创建时间">
              <el-text>{{ userDetail?.createTime }}</el-text>
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
    </el-card>
    <el-card style="width: 80%; margin: 10px auto">
      <el-tabs :model-value="'loginLog'" class="demo-tabs">
        <el-tab-pane label="登录日志" name="loginLog">
          <el-scrollbar :max-height="500">
            <el-card
              v-for="item in loginLogList"
              :key="item.id"
              shadow="hover"
              style="margin: 10px; padding: 10px"
            >
              <el-descriptions :label-width="150">
                <el-descriptions-item label="登录方式：">
                  {{ getLoginMethodMsg(item.loginMethod) }}
                </el-descriptions-item>
                <el-descriptions-item label="登录状态：">
                  <el-tag :type="item.status ? 'success' : 'danger'"
                    >登录{{ item.status ? "成功" : "失败" }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="登录时间："
                  >{{ item.createTime }}
                </el-descriptions-item>
                <el-descriptions-item label="登录IP："
                  >{{ item.loginIp }}
                </el-descriptions-item>
                <el-descriptions-item label="IP来源："
                  >{{ item.ipRegion }}
                </el-descriptions-item>
                <el-descriptions-item label="操作系统：">
                  {{ item.os }}
                </el-descriptions-item>
                <el-descriptions-item label="浏览器：">
                  {{ item.browser }}
                </el-descriptions-item>

                <el-descriptions-item label="错误信息：">
                  {{ item.errorMsg || "无" }}
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-scrollbar>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 修改信息弹窗-->
    <el-dialog
      v-model="updateVisible"
      center
      destroy-on-close
      title="修改个人信息"
      width="35%"
      @close="handleClose(true)"
    >
      <!-- 滚动 -->
      <el-scrollbar max-height="60vh">
        <!-- 表单 -->
        <el-form
          ref="updateFormRef"
          :model="updateInfo"
          :rules="rules"
          label-width="auto"
          style="padding: 10px"
        >
          <el-row :gutter="20">
            <el-scrollbar :max-height="400" style="width: 100%">
              <el-col>
                <el-form-item label="昵称" prop="nickname">
                  <el-input
                    v-model="updateInfo.nickname"
                    clearable
                    placeholder="请输入昵称"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="updateInfo.sex">
                    <el-radio :value="0" label="女" />
                    <el-radio :value="1" label="男" />
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="电话" prop="phone">
                  <el-input
                    v-model="updateInfo.phone"
                    clearable
                    placeholder="请输入电话号码"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="邮箱" prop="email">
                  <el-input
                    v-model="updateInfo.email"
                    clearable
                    placeholder="请输入邮箱"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="头像" prop="avatar">
                  <upload-image
                    :urls="[updateInfo.avatar]"
                    limit="1"
                    @update:url="handleAvatar"
                  />
                </el-form-item>
              </el-col>
            </el-scrollbar>
          </el-row>
        </el-form>
      </el-scrollbar>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div>
          <el-button type="primary" @click="handleUpdateInfoSubmit"
            >确 定
          </el-button>
          <el-button @click="handleClose(true)">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 修改密码弹窗-->
    <el-dialog
      v-model="updatePwdVisible"
      center
      destroy-on-close
      title="修改密码"
      width="35%"
      @close="handleClose"
    >
      <!-- 滚动 -->
      <el-scrollbar max-height="60vh">
        <!-- 表单 -->
        <el-form
          ref="updatePwdRef"
          :model="updatePwdData"
          :rules="pwdRules"
          label-width="auto"
          style="padding: 10px"
        >
          <el-row :gutter="20">
            <el-scrollbar :max-height="400" style="width: 100%">
              <el-col>
                <el-form-item label="旧密码" prop="oldPassword">
                  <el-input
                    v-model="updatePwdData.oldPassword"
                    clearable
                    placeholder="请输入旧密码"
                    show-password
                    type="password"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input
                    v-model="updatePwdData.newPassword"
                    clearable
                    placeholder="请输入新的密码"
                    show-password
                    type="password"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input
                    v-model="updatePwdData.confirmPassword"
                    clearable
                    placeholder="请再次输入新的密码"
                    show-password
                    type="password"
                  />
                </el-form-item>
              </el-col>
            </el-scrollbar>
          </el-row>
        </el-form>
      </el-scrollbar>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div>
          <el-button type="primary" @click="updatePwdSubmit">确 定</el-button>
          <el-button @click="handleClose">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { useUserStore } from "@/store";

import {
  AdminVO,
  BusinessControllerService,
  BusinessUpdateDTO,
  BusinessVO,
  LoginLogControllerService,
  LoginLogVO,
  UpdatePasswordDTO,
  UserInfoControllerService,
} from "@/api";
import { nextTick, ref } from "vue";
import UploadImage from "@/components/UploadImage.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { UserTypeEnum } from "@/types/UserTypeEnum";

const userStore = useUserStore();
const user = userStore.userInfo;
const userDetail = ref<BusinessVO | AdminVO>();

//根据用户Id获取用户信息
function getUserDetailInfo() {
  if (user.role === UserTypeEnum.BUSINESS) {
    // todo ,是否要改成不用传Id
    BusinessControllerService.getBusinessInfoByIdUsingGet(user.id as any).then(
      (res) => {
        userDetail.value = res.data;
      }
    );
  }
  // todo 用户的
}

//修改用户信息
const updateVisible = ref(false);
const updateFormRef = ref();
const updateInfo = ref<BusinessUpdateDTO>({});

// 规则
const rules = {
  email: [
    {
      type: "email",
      message: "邮箱格式不正确",
      trigger: "blur",
    },
  ],
  phone: [
    {
      len: 11,
      message: "手机号码长度不正确",
      trigger: "blur",
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "手机号码格式不正确",
      trigger: "blur",
    },
  ],
};

//修改用户弹窗
function openUpdateModel() {
  updateInfo.value = {
    id: userDetail.value?.id,
    nickname: userDetail.value?.nickname,
    phone: userDetail.value?.phone || "",
    email: userDetail.value?.email || "",
    avatar: userDetail.value?.avatar || "",
  };
  updateVisible.value = true;
}

//更改用户头像
function handleAvatar(urls: string[]) {
  updateInfo.value!.avatar = urls[0];
}

//关闭弹窗事件
const closeFlag = ref(false);

function handleClose(infoFlag?: boolean) {
  if (closeFlag.value) {
    closeFlag.value = false;
    return;
  }
  ElMessageBox.confirm(
    `确定要关闭修改个人${infoFlag === true ? "信息" : "密码"}弹窗吗？`
  )
    .then(() => {
      if (infoFlag === true) updateVisible.value = false;
      else updatePwdVisible.value = false;
      closeFlag.value = true;
    })
    .catch(() => {
      ElMessage.info("取消了关闭弹窗");
    });
}

//修改信息提交
function handleUpdateInfoSubmit() {
  updateFormRef.value.validate((validate: boolean) => {
    if (validate) {
      if (user.role === UserTypeEnum.BUSINESS) {
        BusinessControllerService.updateBusinessUsingPut(updateInfo.value).then(
          (res) => {
            //提醒
            ElMessage.success(res.data);
            //关闭弹窗
            updateVisible.value = false;
            //刷新数据
            getUserDetailInfo();
          }
        );
      }
    }
  });
}

const updatePwdData = ref<UpdatePasswordDTO>({});
const updatePwdVisible = ref(false);
const updatePwdRef = ref();

//二次密码确认校验
function validatePwd(rule: any, value: any, callback: any) {
  if (value === "") {
    callback(new Error("请再次输入密码"));
    return;
  }
  if (value !== updatePwdData.value.newPassword) {
    callback(new Error("两次密码不一致"));
    return;
  }
  callback();
}

//规则
const pwdRules = {
  oldPassword: [
    {
      required: true,
      trigger: "blur",
      message: "请输入旧的密码",
    },
    {
      min: 8,
      message: "密码不能小于8位",
      trigger: "blur",
    },
  ],
  newPassword: [
    {
      required: true,
      trigger: "blur",
      message: "请输入新的密码",
    },
    {
      min: 8,
      message: "密码不能小于8位",
      trigger: "blur",
    },
  ],
  confirmPassword: [
    {
      required: true,
      trigger: "blur",
      message: "请再次输入密码",
    },
    {
      min: 8,
      message: "密码不能小于8位",
      trigger: "blur",
    },
    { validator: validatePwd, trigger: "blur" },
  ],
};

//打开确认密码弹窗
function openUpdatePwd() {
  //设置用户ID
  updatePwdData.value.id = userDetail.value?.id;
  // 打开弹窗
  updatePwdVisible.value = true;
}

const router = useRouter();
const route = useRoute();

// 修改密码提交
function updatePwdSubmit() {
  updatePwdRef.value.validate((validate: boolean) => {
    if (validate) {
      (user.role === UserTypeEnum.BUSINESS
        ? BusinessControllerService.updateBusinessSelfPwdUsingPut(
            updatePwdData.value
          )
        : UserInfoControllerService.updateUserInfoSelfPwdUsingPut(
            updatePwdData.value
          )
      ).then((res) => {
        ElMessage.success(res.data);
        nextTick(() => {
          //退出登录
          userStore.logout();
          //获取路径参数
          const params = new URLSearchParams(
            route.query as Record<string, string>
          ).toString();
          //拼接重定向路径
          const redirect = params ? `${route.path}?${params}` : route.path;
          router.push(`/basic/login?redirect=${encodeURIComponent(redirect)}`);
        });
      });
    }
  });
}

getUserDetailInfo();
//获取登录日志信息
const loginLogList = ref<LoginLogVO[]>([]);

function getLoginLogList() {
  LoginLogControllerService.getLoginLogByKeywordUsingGet().then((res) => {
    loginLogList.value = res.data || [];
  });
}

//  获取登录方式
function getLoginMethodMsg(value: number) {
  if (value === 0) {
    return "账号登录";
  }
  if (value === 1) {
    return "邮箱登录";
  }
  if (value === 2) {
    return "手机号登录";
  }
  return "未知";
}

getLoginLogList();
</script>

<style lang="scss" scoped>
#info {
  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
  }
}
</style>
